package com.plusjun.ssoserver.controller;

import lombok.Data;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/info")
    @ResponseBody
    public String info(@RequestParam("token") String token) {
        String s = stringRedisTemplate.opsForValue().get(token);
        return s;
    }

    @PostMapping("/doLogin")
    public String login(UserVO userVO,
                        HttpServletResponse response) {
        if (!StringUtils.isEmpty(userVO.getUsername()) && !StringUtils.isEmpty(userVO.getPassword())) {
            String uuid = UUID.randomUUID().toString().replace("-", "");
            stringRedisTemplate.opsForValue().set(uuid, userVO.getUsername(),10, TimeUnit.MINUTES);
            Cookie cookie = new Cookie("sso_token", uuid);
            response.addCookie(cookie);
            // 登录成功就跳回之前页面
            return "redirect:" + userVO.getUrl() + "?token=" + uuid;
        }
        return "login";
    }

    @GetMapping("/login.html")
    public String tologinPage(@RequestParam("redirect_url") String url, Model model,
                              @CookieValue(value = "sso_token", required = false) String sso_token) {
        if (!StringUtils.isEmpty(sso_token)) {
            return "redirect:" + url + "?token=" + sso_token;
        }
        model.addAttribute("url", url);

        // 登录成功就跳回之前页面
        return "login";
    }
}

@Data
class UserVO {
    private String username;
    private String password;
    private String url;
}